package com.idbk.chargestation.app;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;

import com.android.volley.VolleyError;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.bean.JsonADsWelcome;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 广告管理器
 *
 * @author lupc
 */
public final class ManagerADs {

    public final static String TAG = ManagerADs.class.getSimpleName();

    public final static String AD_IMAGE_NAME_WELCOME_1 = "ad_image_welcome_0.jpg";


    private Context mContext;

    /**
     * 广告管理器
     *
     * @param context 应用程序上下文
     */
    public ManagerADs(Context context) {
        mContext = context;
    }

    public void refresh() {
        JsonADsWelcome data = getWelcomeADInfo();
        ChargeStationAPI.getWelcomeADsInfo(data.id, mResponseWelcome);
    }

    private final EHttpResponse mResponseWelcome = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonADsWelcome result = GsonUtils.toBean(JsonADsWelcome.class, response);
            if (result != null && result.status == GlobalResult.OK.getStatus()) {
                //和以前的做对比
                JsonADsWelcome pre = getWelcomeADInfo();
                if (pre != null && pre.id == result.id) {
                    //如果广告信息没有改变，则保存，但是不下载图片
                    saveWelcomeADInfo(result);
                } else {
                    //保存广告信息，并下载广告图片
                    saveWelcomeADInfo(result);
                    if (result.isShow) {
                        String dir = mContext.getExternalFilesDir(null).getPath();
                        downloadFile(result.imageURL, dir, AD_IMAGE_NAME_WELCOME_1);
                    }
                }
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Log.e(TAG, error.getMessage(), error.getCause());
        }

    };


    private void saveWelcomeADInfo(JsonADsWelcome data) {
        SharedPreferences sp = mContext.getSharedPreferences(ConfigSharedPreferences.CHARGE_STATION, Context.MODE_PRIVATE);
        sp.edit()
                .putInt(ConfigSharedPreferences.KEY_AD_WELCOME_ID, data.id)
                .putString(ConfigSharedPreferences.KEY_AD_WELCOME_IMAGE_URL, data.imageURL)
                .putString(ConfigSharedPreferences.KEY_AD_WELCOME_LINK_URL, data.linkURL)
                .putBoolean(ConfigSharedPreferences.KEY_AD_WELCOME_IS_SHOW, data.isShow)
                .putBoolean(ConfigSharedPreferences.KEY_AD_WELCOME_IS_REFRESH, data.isRefreshed)
                .apply();
    }

    private static void downloadFile(final String destURL, final String dir, final String fileName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url;
                InputStream in = null;
                FileOutputStream out = null;
                HttpURLConnection conn = null;
                try {
                    url = new URL(destURL);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.connect();
                    long fileLength = conn.getContentLength();
                    in = conn.getInputStream();
                    //
                    File file = new File(dir, fileName);

                    out = new FileOutputStream(file);
                    byte[] buffer = new byte[1024];
                    int len;
                    long readLength = 0L;
                    while ((len = in.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                        readLength += len;
                        if (readLength >= fileLength) {
                            break;
                        }
                    }
                    out.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }).start();
    }

    public JsonADsWelcome getWelcomeADInfo() {
        JsonADsWelcome data = new JsonADsWelcome();
        SharedPreferences sp = mContext.getSharedPreferences(ConfigSharedPreferences.CHARGE_STATION, Context.MODE_PRIVATE);
        data.id = sp.getInt(ConfigSharedPreferences.KEY_AD_WELCOME_ID, 0);
        data.imageURL = sp.getString(ConfigSharedPreferences.KEY_AD_WELCOME_IMAGE_URL, "");
        data.linkURL = sp.getString(ConfigSharedPreferences.KEY_AD_WELCOME_LINK_URL, "");
        data.isShow = sp.getBoolean(ConfigSharedPreferences.KEY_AD_WELCOME_IS_SHOW, false);
        data.isRefreshed = sp.getBoolean(ConfigSharedPreferences.KEY_AD_WELCOME_IS_REFRESH, false);
        return data;
    }


    public Uri getWelcomeADImage() {
        File file = new File(mContext.getExternalFilesDir(null), AD_IMAGE_NAME_WELCOME_1);
        return Uri.fromFile(file);
    }

}
